package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.android.uu.utils.uuUtils;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.HemaWebView;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.ReplyAdapter;
import com.hemaapp.yjnh.bean.AttributeItems;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.ImageCarouselBanner;
import com.hemaapp.yjnh.view.ShareDialog;
import com.hemaapp.yjnh.view.YjnhListView;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

/**
 * 预约类商品详情
 */
public class BookProductionDetailActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_right_img)
    ImageView titleRightImg;
    @Bind(R.id.title_right_img2)
    ImageView titleRightImg2;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.image_carousel_banner)
    ImageCarouselBanner imageCarouselBanner;
    @Bind(R.id.tv_goods_name)
    TextView tvGoodsName;
    @Bind(R.id.tv_price_new)
    TextView tvPriceNew;
    @Bind(R.id.tv_price_old)
    TextView tvPriceOld;
    @Bind(R.id.tv_coupons_count)
    TextView tvCouponsCount;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_sell_count)
    TextView tvSellCount;
    @Bind(R.id.iv_merchant_avatar)
    ImageView ivMerchantAvatar;
    @Bind(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.iv_merchant_drawright)
    ImageView ivMerchantDrawright;
    @Bind(R.id.layout_merchant)
    LinearLayout layoutMerchant;
    @Bind(R.id.line_info)
    View lineInfo;
    @Bind(R.id.line_reply)
    View lineReply;
    @Bind(R.id.layout_property)
    LinearLayout layoutProperty;
    @Bind(R.id.tv_buycontent)
    TextView tvBuycontent;
    @Bind(R.id.webview)
    HemaWebView webview;
    @Bind(R.id.listview)
    YjnhListView listview;
    @Bind(R.id.scrollview)
    ScrollView scrollview;
    @Bind(R.id.refreshLoadmoreLayout)
    RefreshLoadmoreLayout refreshLoadmoreLayout;
    private View layoutProductionDetail;

    private String mBlogId = "0";//商品id
    private BlogDetail detail;
    private ArrayList<AttributeItems> attributes = new ArrayList<>();//商品属性
    private ArrayList<Reply> replies = new ArrayList<>();
    private ReplyAdapter adapter;
    private User user;
    private LoginUtil.LoginCallBack loginCallBack;
    int page = 0;
    private int type = 1;//1普通预约商家, 2走走露营商家

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_book_production_detail);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        init();
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
    @Override
    protected void findView() {
        layoutProductionDetail = findViewById(R.id.content_detail);
    }

    @Override
    protected void getExras() {
        type = mIntent.getIntExtra("type", 1);
        mBlogId = mIntent.getStringExtra("blog_id");
        if (isNull(mBlogId)) {
            XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍后再试");
            finish();
        }
    }

    @Override
    protected void setListener() {
        titleText.setText("商品详情");
        titleRightBtn.setVisibility(View.GONE);
        titleRightImg.setVisibility(View.VISIBLE);
        titleRightImg2.setVisibility(View.VISIBLE);
        titleRightImg2.setImageResource(R.drawable.share);
        listview.setFocusable(false);
        refreshLoadmoreLayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {

            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                init();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                page++;
                getNetWorker().replyList("2", mBlogId, page + "");
            }
        });
        initWebView();
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        // 支持javascript
        webview.getSettings().setJavaScriptEnabled(true);
        // 设置可以支持缩放
        webview.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webview.getSettings().setBuiltInZoomControls(false);
        // 扩大比例的缩放
        webview.getSettings().setUseWideViewPort(true);
        // 自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        // 取消显示滚动条
        webview.setVerticalScrollBarEnabled(false);
        webview.setHorizontalScrollBarEnabled(false);
        //不获取焦点
        webview.setFocusable(false);
    }

    private void init() {
        page = 0;
        String token = user == null ? "" : user.getToken();
        getNetWorker().getBlogDetail(token, mBlogId);
    }

    private void initImagePager() {
        ArrayList<String> urls = new ArrayList<>();
        for (ImgItemsBean item : detail.getImgItems()) {
            urls.add(item.getImgurl());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselBlogClickListener(mContext, (ArrayList<ImgItemsBean>) detail.getImgItems()));
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case REPLY_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case REPLY_LIST:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                HemaArrayResult<BlogDetail> bResult = (HemaArrayResult<BlogDetail>) baseResult;
                detail = bResult.getObjects().get(0);
                if (detail == null) {
                    XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍后再试");
                    finish();
                } else {
                    initImagePager();
                    setData();
                    initPropertyList();//商品属性
                    getNetWorker().replyList("2", mBlogId, page + "");
                }
                break;
            case REPLY_LIST:
                String page = netTask.getParams().get("page");
                HemaPageArrayResult<Reply> nResult = (HemaPageArrayResult<Reply>) baseResult;
                if (nResult == null || nResult.getObjects() == null)
                    return;
                ArrayList<Reply> replies = nResult.getObjects();
                if ("0".equals(page)) {// 刷新
                    refreshLoadmoreLayout.refreshSuccess();
                    this.replies.clear();
                    this.replies.addAll(replies);
                } else {// 更多
                    refreshLoadmoreLayout.loadmoreSuccess();
                    if (replies.size() > 0)
                        this.replies.addAll(replies);
                    else {
                        refreshLoadmoreLayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshData(-1);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String oper = netTask.getParams().get("oper");
                // 操作	1添加 ，2取消 ;3：清空
                if (oper.equals("1")) {
                    XtomToastUtil.showShortToast(mContext, "添加收藏成功!");
                    titleRightImg.setImageResource(R.drawable.star_while);
                    ScaleAnimation scaleAnimation = new ScaleAnimation(0.0f, 1.4f, 0.0f, 1.4f,
                            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                    scaleAnimation.setDuration(300);//设置动画持续时间
                    titleRightImg.startAnimation(scaleAnimation);
                    detail.setCollectflag("1");
                } else {
                    XtomToastUtil.showShortToast(mContext, "取消收藏成功!");
                    titleRightImg.setImageResource(R.drawable.star_while_stroke);
                    detail.setCollectflag("0");
                }
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                refreshLoadmoreLayout.refreshFailed();
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，" + baseResult.getMsg());
                finish();
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败，" + baseResult.getMsg());
                break;
            case REPLY_LIST:
                if (page == 0)
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                XtomToastUtil.showShortToast(mContext, "获取评论失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                XtomToastUtil.showShortToast(mContext, "获取商品信息失败，请稍候再试");
                finish();
                break;
            case REPLY_LIST:
                if (page == 0)
                    refreshLoadmoreLayout.refreshFailed();
                else
                    refreshLoadmoreLayout.loadmoreFailed();
                refreshData(failedType);
                XtomToastUtil.showShortToast(mContext, "获取评论失败，请稍候再试");
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                XtomToastUtil.showShortToast(mContext, "操作失败失败，请稍候再试");
                break;
        }
    }

    private void refreshData(int failed) {
        if (adapter == null) {
            adapter = new ReplyAdapter(mContext, replies);
            adapter.setEmptyString("没有评价");
            listview.setAdapter(adapter);
        } else {
            adapter.setEmptyString("没有评价");
            adapter.notifyDataSetChanged();
        }
        adapter.setFailtype(failed);
    }

    private void setData() {
        String collectFlag = detail.getCollectflag();
        if (collectFlag == null || collectFlag.equals("0")) {
            titleRightImg.setImageResource(R.drawable.star_while_stroke);
        }else {
            titleRightImg.setImageResource(R.drawable.star_while);
        }
        tvGoodsName.setText(detail.getName());
        tvPriceNew.setText("¥"+uuUtils.formatAfterDot2(detail.getPrice()));
        tvPriceOld.setText("¥"+ uuUtils.formatAfterDot2(detail.getOldprice()));
        tvPriceOld.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG );
        tvCouponsCount.setText("可使用");
        BaseUtil.addStampSign(mContext, tvCouponsCount, R.drawable.food_stamp_grey);
        tvCouponsCount.append(detail.getScore()+"粮票");
        if (isNull(detail.getEnddate()))
            tvDate.setVisibility(View.INVISIBLE);
        else
            tvDate.setText("门票有效时间："+BaseUtil.transNull(detail.getEnddate()));
        tvSellCount.setText("销量："+detail.getSellcount());
        ImageUtils.loadAvatar(mContext, detail.getAvatar(), ivMerchantAvatar);
        tvMerchantName.setText(detail.getNickname());
        String star = detail.getFarmer_starscore();
        if (!isNull(star)) {
            ratingBar.setRating(Float.parseFloat(star));
        }
        //如果是平台自营商品，那么商家部分显示拨打电话
        if (detail.getType().equals("2")) {
            ivMerchantDrawright.setImageResource(R.drawable.phone_grey);
        }
        //商品信息
        tvBuycontent.setText(detail.getBuycontent());
        String sys_web_service = BaseApplication.getInstance().getSysInitInfo().getSys_web_service();
        String path = sys_web_service + "webview/parm/blogdetail_" + detail.getId();
        webview.loadUrl(path);
        if (listview.getVisibility() == View.GONE)
            layoutProductionDetail.setVisibility(View.VISIBLE);
    }

    //初始化商品属性
    private void initPropertyList() {
        attributes = (ArrayList<AttributeItems>) detail.getAttributeItems();
        if (attributes != null && attributes.size() > 0) {
            layoutProperty.removeAllViews();
            for (AttributeItems attribute : attributes) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.production_detail_item, null);
                ((TextView) view.findViewById(R.id.name)).setText(attribute.getname());
                ((TextView) view.findViewById(R.id.content)).setText(attribute.getcontent());
                layoutProperty.addView(view);
            }
            layoutProperty.setVisibility(View.VISIBLE);
        }else
            layoutProperty.setVisibility(View.GONE);
    }

    @OnClick({R.id.title_left_btn, R.id.title_right_img, R.id.title_right_img2,
            R.id.layout_merchant, R.id.layout_info, R.id.layout_reply,
            R.id.ll_return_top, R.id.iv_consult, R.id.tv_buy, R.id.tv_question})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                if (BaseUtil.isLogin()) {
                    String token = user.getToken();
                    if ("0".equals(detail.getCollectflag())) {//未关注
                        getNetWorker().FolColOperate(token, "2", "1", detail.getId());
                    } else {//已关注
                        getNetWorker().FolColOperate(token, "2", "2", detail.getId());
                    }
                } else {
                    Intent itCart = new Intent(mContext, LoginActivity.class);
                    startActivity(itCart);
                }
                break;
            case R.id.title_right_img2:
                String sys_plugins = getApplicationContext().getSysInitInfo().getSys_plugins();
                String username = user == null? "":user.getUsername();
                String path = sys_plugins + "share/sdk.php?id=" + mBlogId + "&customflag=0&username="+username;
                //图片url
                UMImage image = null;
                String imgUrl = detail.getImgurl();
                if (!isNull(imgUrl)) {
                    image = new UMImage(mContext, imgUrl);
                } else {
                    imgUrl = BaseUtil.getLogoImagePath(mContext);
                    image = new UMImage(mContext, BitmapFactory.decodeFile(imgUrl));
                }
                new ShareDialog(this, "分享商品", detail.getName(), path, image)
                        .builder().show();
                break;
            case R.id.ll_return_top:
                scrollview.smoothScrollTo(0, 0);
                break;
            case R.id.layout_merchant:
                if (detail == null)
                    return;
                if (detail.getType().equals("2")) {//平台商品
                    final String phone = detail.getMobile();
                    if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                        hbDialog.setText("是否直接拨打"+phone+"?");
                        hbDialog.setLeftButtonText("取消");
                        hbDialog.setRightButtonText("拨打");
                        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                            @Override
                            public void onLeftButtonClick(HemaButtonDialog dialog) {
                                dialog.cancel();
                            }

                            @Override
                            public void onRightButtonClick(HemaButtonDialog dialog) {
                                dialog.cancel();
                                Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse(
                                        "tel:" + phone));
                                startActivity(intent);
                            }
                        });
                    }else {
                        XtomToastUtil.showShortToast(mContext, "对方没有提供电话号码");
                    }
                }else {//第三方商品
                    Intent itMerchant = new Intent();
                    if (type == 1) {
                        itMerchant.setClass(mContext, CmnBookMerchantDetailActivity.class);
                    }else if (type == 2){//走走露营商家
                        itMerchant.setClass(mContext, ZouzouCampsiteMerchantDetailActivity.class);
                    }else
                        return;
                    itMerchant.putExtra("client_id", detail.getClient_id());
                    startActivity(itMerchant);
                }
                break;
            case R.id.layout_info:
                lineInfo.setVisibility(View.VISIBLE);
                lineReply.setVisibility(View.GONE);
                listview.setVisibility(View.GONE);
                layoutProductionDetail.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_reply:
                lineInfo.setVisibility(View.GONE);
                lineReply.setVisibility(View.VISIBLE);
                listview.setVisibility(View.VISIBLE);
                layoutProductionDetail.setVisibility(View.GONE);
                break;
            case R.id.iv_consult:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        String mQQNum = detail.getQq();
                        if (isNull(mQQNum)) {
                            XtomToastUtil.showShortToast(mContext, "对方没有指定QQ");
                            return;
                        }
                        String url="mqqwpa://im/chat?chat_type=wpa&uin="+mQQNum;
                        try {
                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        } catch (Exception e) {
                            showTextDialog("打开QQ客户端失败\n请确保已经安装了QQ手机客户端");
                            e.printStackTrace();
                        }
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.tv_buy:
                if (detail.getSaleflag().equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "商品已下架");
                    return;
                }
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        Intent intent = new Intent(mContext, BookConfirm1Activity.class);
                        intent.putExtra("blog", detail);
                        startActivity(intent);
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.tv_question:
                Intent intent = new Intent(mContext, QuestionActivity.class);
                intent.putExtra("QQ", detail.getQq());
                intent.putExtra("blog_id", detail.getId());
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            init();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }
    }
}
